package com.netdisk.controller;

import java.util.HashMap;
import java.util.Map;
import static com.netdisk.util.CapacityCount.countCapacityToUnit;
import com.netdisk.util.CapacityCount;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.netdisk.entity.Capacity;
import com.netdisk.entity.User;
import com.netdisk.service.impl.CapacityService;
import com.opensymphony.xwork2.ActionSupport;

@Component("capacityJsonAction")
@Scope("prototype")
public class CapacityJsonAction  extends ActionSupport{
	private CapacityService capacityService;
	
	@Resource(name="capacityService")
	public void setCapacityService(CapacityService capacityService) {
		this.capacityService = capacityService;
	}
	
	private Map<String, String> capacity = new HashMap<String, String>();
	
	public Map<String, String> getCapacity() {
		return capacity;
	}

	public void setCapacity(Map<String, String> capacity) {
		this.capacity = capacity;
	}


	@Override
	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession	session =  request.getSession();
		User user = (User)session.getAttribute("user");
		Capacity cap = capacityService.findByOwnerId(user.getId());
		long alreadyUse= cap.getAlreadyUse();
		
		if( alreadyUse / 1024L / 1024L /1024L /1024L > 1 ){
			
			capacity.put("alreadyUse", countCapacityToUnit ( cap.getAlreadyUse(), CapacityCount.TB ).intValue() + "TB");
			
		}else if(alreadyUse / 1024L / 1024L / 1024L > 1){
			
			capacity.put("alreadyUse", countCapacityToUnit ( cap.getAlreadyUse(), CapacityCount.GB ).intValue() + "GB");
			
		}else if(alreadyUse / 1024L / 1024L > 1){
			
			capacity.put("alreadyUse", countCapacityToUnit ( cap.getAlreadyUse(), CapacityCount.MB ).intValue() + "MB");
			
		}else if(alreadyUse / 1024L > 1){
			
			capacity.put("alreadyUse", countCapacityToUnit ( cap.getAlreadyUse(), CapacityCount.KB ).intValue() + "KB");
			
		}else{
			
			capacity.put("alreadyUse", countCapacityToUnit ( cap.getAlreadyUse(), CapacityCount.B ).intValue() + "B" );
			
		}
		
		capacity.put("maxCapacity", countCapacityToUnit ( cap.getMaxCapacity(), CapacityCount.GB ).intValue() + "GB" );
		return SUCCESS;
	}
	
}
